$(function(){
	var togglePlace = function(){
		var that = this;
		this.box = $('.hidden-place-box');
		this.button = $('#show-more-place');
		this.button.click(function(e){
			e.preventDefault();
			that.show();
		})
	}
	togglePlace.prototype = {
		constructor:togglePlace,
		show:function(){
			console.log(this.box)
			this.box.css('height', 'auto');
			this.button.hide()
		},
		hide:function(){
			this.box.css('height', '100px');
			this.button.show();
		}
	};
	var oldTogglePlace = new togglePlace();
	window.oldTogglePlace = oldTogglePlace;


	(function(){
		function dataBind(thisItem,thisData){
			thisItem.attr({
				'data-addressId'  : thisData.address_id,
				'data-addressPid' : thisData.pid
			});
			thisItem.find(".js-addressId").val(thisData.id)
			//thisItem.find('.js-receive-name').html(thisData.receiver)
			//thisItem.find('.js-receive-tel').html(thisData.phone)
			thisItem.find('.js-receive-address').html(thisData.address_string)
			if(thisData['default']==1){
				thisItem.addClass(selectAttr)
				thisItem.find(".js-addressId").prop('checked', true)
			}
		}
		function select(that,ready){
			that.siblings().removeClass(selectAttr)
			that.addClass(selectAttr)
			that.find('input').prop('checked', true).attr('checked', true);

			//过滤服务站
			if(ready==1)
				baiduMap.refresh(that.attr('data-addressid')||null, that.attr('data-addresspid') )
		}
		var box = $('.old-places-box');
		var addressTpl = $('.old-place').remove();
		var selectAttr = 'selected-place'
		api.solo('userAddress',[],function(d){
			var list = d.data.list;
			var length = list.length;
			
			for(var i=0;i<length;i++){
				var thisItem = addressTpl.clone();
				var thisData = list[i]
				dataBind(thisItem,thisData)
				box.append(thisItem)
			}
			//选择操作
			$('.old-places-box').on('click', '.old-place', function(event) {
				//event.preventDefault();
				console.log('click1')
				clickThisAddress($(this),1)
			});
			function clickThisAddress(that,ready){
				console.log('click')
				select(that,ready)
				var addressId = that.attr('data-addressId');
				//chainAddress.getRecommend(addressId);
			}
			//默认选一个吧
			//$('.old-place').eq(0).click()
			clickThisAddress($('.old-place').eq(0),0)

			//隐藏地址
			if(length>3){
				oldTogglePlace.hide()
			}else{
				oldTogglePlace.show()
			}

		})
		//添加新地址
		$('.truely-add').click(function(event) {
			event.preventDefault();
			var addressInput = {}
			addressInput[0] = $('#consignee-name').val()
			addressInput[1] = $('#consignee-phone').val()
			//addressInput.province = $('#consignee-province')
			addressInput[2] = $('.js-select-address:last').val()
			addressInput[3] = $("#consignee-address").val()
			for(var i in addressInput){
				if(typeof addressInput[i] == 'undefined' || addressInput[i] == ''){
					alert('请填写完整您的信息')
					return;
				}
			}
			api.solo('addAddress',addressInput,function(addData){
				if(addData.state!=200){
					alert('添加失败')
					return;
				}
				var newItem = addressTpl.clone()
				api.solo('userAddress',[],function(d){
					var list = d.data.list;
					var length = list.length;
					var newData = list[length-1]
					console.log(newData)
					dataBind(newItem,newData)
					box.append(newItem)
					newItem.click()
					select(newItem)

					oldTogglePlace.show();
				})
				
			})
		});
	})();

	//地址联动
	var chainAddress = (function(){
		var box = $('.js-select-address-box')
		var tpl = $('.js-select-address').remove()
		var optionTpl = $("<option></option>");
		var currentId = 0;
		function getSonIds(){
			api.solo('area',[currentId],function(d){
				var list = d.data.list;
				var length = list.length;
				if(length<1) return;
				var newSelect = tpl.clone()
				for(var i=0;i<length;i++){
					var thisOption = optionTpl.clone();
					thisOption.val(list[i]['id']).html(list[i]['name'])
					newSelect.append(thisOption)
				}
				//特殊设置
				if(currentId==0) addNoAddress(newSelect)
				box.append(newSelect)
				currentId = list[0]['id']
				getSonIds()
			})
		}
		//初始化
		getSonIds()
		box.on('change', '.js-select-address', function(event) {
			console.log('change')
			currentId = $(this).val();
			$(this).nextAll().remove()
			getSonIds()
			selectService()
		});
		//特殊化 第一条
		function addNoAddress(that){
			var specialOption = optionTpl.clone().val(-1).html('其他地区')
			that.append(specialOption)
		}

		//选择推荐的服务站
		var textRecommend = $("<span class='js-rec'>（系统推荐）</span>")
		var optionNo      = $('#station-address option:first')
		var service       = {};
		service.items     = $('#station-address')
		service.reset = function(){
			service.items.find('.js-rec').remove()
			optionNo.show()
		}
		service.choose = function(address_id){
			var item  = service.items.find("[address_id="+address_id+"]")
			if(item.length > 0){
				item.append(textRecommend)
				item.attr('selected', true);
				item.prop('selected', true);
				optionNo.hide()
			}else{
				optionNo.attr('selected', true);
				optionNo.prop('selected', true);
				optionNo.show()
			}
			
		}
		function selectService(){
			service.reset()
			if($('.js-select-address:first').find('option:selected').val() == 1){
				console.log('选择了灵璧县开始找推荐服务站！')
				service.choose($('.js-select-address:last').find('option:selected').val())
			}else{
				service.choose(-1)
			}
		}	
		function selectServiceByOldAddress(addressId){
			service.reset()
			service.choose(addressId)
		}
		return {
			getRecommend:selectServiceByOldAddress
		}
		
	})();
	console.log('chainAddress:',chainAddress);
	var baiduMap = (function(){
	    //百度地图API功能
	    var map = new BMap.Map("allmap");
	    map.addControl(new BMap.NavigationControl());
	    map.enableScrollWheelZoom();    //启用滚轮放大缩小
	    map.enableContinuousZoom();    //启用地图惯性拖拽
	    //map.setZoom(10);
		api.solo( "siteInfo", [], function(d){
			var siteInfo= d.data;
			map.centerAndZoom(new BMap.Point(siteInfo.lon,siteInfo.lat),11);
		});
	    map.centerAndZoom(new BMap.Point(117.565297,33.547786),13);
	    var localSearch = new BMap.LocalSearch(map);
	    localSearch.enableAutoViewport();

	    // 读取服务站列表
	    var $stationSelect=$("#station-address");
	    var $stationSelectTpl=$stationSelect.find("option");
	    var mapData = {}
	    api.solo( "serviceList", [], function(d){
	    	console.log(d);
	    	mapData = d;
	    	addOverLay( $('.selected-place').attr('data-addressid')||null ,$('.selected-place').attr('data-addresspid')||null )

	        //if(_userInfo.service_id){
	        //	$stationSelect.val(_userInfo.service_id);	
	        //}else{
	        //	$stationSelect.val(0);	
	        //}
	        //$stationSelect.val(0);
	        var $currentOption=$stationSelect.find("[value="+_userInfo.service_id+"]");
	        var serviceInfo=$currentOption.data("serviceInfo");
	        if(serviceInfo)
	        	$currentOption.text(serviceInfo.service_name+" "+serviceInfo.address_string+serviceInfo.address_text+" "+"(默认服务站)")
	    });

	    function addOverLay(filterAddressId,filterAddressPid){
	    	$stationSelect.empty();
	    	map.clearOverlays();
	    	console.log(filterAddressId,filterAddressPid)

	    	///////////////////////filter//////////////////////
	    	var isFilterId  = false; //村级别过滤
	    	var isFilterPid = false; //镇级别过滤
	    	var countyName = '灵璧县'; //镇名字！
	    	var hasService = false;   //有无默认服务站
	    	if(filterAddressId){
	    		for(var i in mapData.data.list){
	    			//console.log(filterAddressPid,mapData.data.list[i]['pid'])
	    			if(filterAddressPid == mapData.data.list[i]['pid']){
	    				isFilterPid = true;
	    				countyName = mapData.data.list[i]['address_string'];
	    			}
	    			if(filterAddressId == mapData.data.list[i]['address_id']){
	    				isFilterId  = true;
	    				countyName = mapData.data.list[i]['address_string'];
						break;
	    			}
	    		}
	    	}else{
	    		$stationSelect.append('<option value="" >请先填写您的地址</option>');
	    		return;
	    	}
	    	////////////////////////////////////////////////////


	    	for(var i in mapData.data.list){
	    		//不要放过默认服务站
	    		//console.log('这个服务站叫'+mapData.data.list[i]['address_string'])
	    		if( _userInfo.service_id && mapData.data.list[i]['id']==_userInfo.service_id  ){
	    			//这条是默认服务站
	    			//console.log('找到一个默认服务站')
	    			hasService = true;
	    		}else{
	    			//过滤服务站
	    			//console.log('不是默认服务站开始过滤')
	    			if(isFilterPid){
	    				//console.log('存在同镇的')
	    				if(filterAddressPid != mapData.data.list[i]['pid']){
	    					//console.log('不是同镇的跳过')
	    					continue;
	    				}else{
	    					//console.log('是同村的继续')
	    				}
	    			}else{
	    				continue;
	    			}
	    			//else{
	    			//	$stationSelect.append('<option value="" >不使用服务站</option>');
	    			//	return;
	    			//}
	    		}

	    		


	    	    // 标注地图
	    	    serviceInfo=mapData.data.list[i];
	    	    var point = new BMap.Point(serviceInfo.longitude,serviceInfo.latitude);
	    	    var marker = new BMap.Marker(point);  // 创建标注
	    	    map.addOverlay(marker);              // 将标注添加到地图中
	    	    marker.serviceInfo=serviceInfo;
	    	    marker.addEventListener("click", function(e){
	    	        var p = e.target;
	    	        console.log(p.serviceInfo);
                    console.log($stationSelect,p.serviceInfo.id);
	    	        $stationSelect.val(p.serviceInfo.id);
                    $stationSelect.find(' option[value="'+p.serviceInfo.id+'"] ').attr('selected',true).prop('selected',true);
	    	    });

	    	    //小窗口
	    	    var score=serviceInfo.comment==0?5:serviceInfo.score/serviceInfo.comment
	    	    var opts = {
	    	        width : 200,     // 信息窗口宽度
	    	        height: 100,     // 信息窗口高度
	    	        title : serviceInfo.service_name ,
	    	        enableMessage:false,
	    	        'message': serviceInfo.tel+"评价"+score+"星"
	    	    };
	    	    //var s="<br/><a target='_blank' href='"+_root+"../my/setDefaultService?service_id="+serviceInfo.id+"'>设置默认服务站</a>";
	    	    marker.infoWindow = new BMap.InfoWindow(serviceInfo.tel+"<br/>"+serviceInfo.address_string+"<br/>"+"评价"+score+"星", opts);  // 创建信息窗口对象
	    	    marker.addEventListener("click", function(e){
	    	        var p = e.target;
	    	        map.openInfoWindow(p.infoWindow, p.getPosition()); //开启信息窗口
	    	    });

	    	    // 增加显示
	    	    var $tmp=$stationSelectTpl.clone().removeAttr('selected').removeProp('selected');
	    	    $tmp.data("serviceInfo",serviceInfo);
	    	    //console.log(serviceInfo);
	    	    $tmp.attr("value",serviceInfo.id);
	    	    $tmp.attr('address_id', serviceInfo.address_id);
	    	    $tmp.text(serviceInfo.service_name+" "+serviceInfo.address_string+(serviceInfo.address_text||"")+" ");
	    	    $stationSelect.append($tmp);
	    	}
	    	//$stationSelect.append('<option value="" >不使用服务站</option>');
	    	$stationSelect.find('option').show()

	    	//定位
	    	searchByStationName(countyName)

	    	//村级服务站
	    	console.log('村级服务站',isFilterId,filterAddressId,$('#station-address').find("option[value='"+filterAddressId+"']"))
	    	if(isFilterId){
	    		$('#station-address').find("option[address_id='"+filterAddressId+"']")
	    		.append(' (系统推荐) ')
	    		.attr('selected', 'selected')
	    		.prop('selected', 'selected')
	    	}

	    	//默认服务站
	    	console.log(_userInfo.service_id)
	    	if(hasService){
	    		//是不是只有默认服务站
	    		if( $('#station-address').find("option").length==1 ){
	    			$stationSelect.append('<option value="" >不使用服务站</option>');
	    		}

	    		var defaultAddressOption = $('#station-address').find("option[value='"+_userInfo.service_id+"']");
	    		if(defaultAddressOption.length > 0){
	    			defaultAddressOption.attr('selected', 'selected').prop('selected', 'selected')
	    			.append('(默认服务站)');
	    		}
	    	}else{
	    		if( $('#station-address').find("option").length<1 ){
	    			$stationSelect.append('<option value="" >不使用服务站</option>');
	    		}
	    	}
	    }

	    function searchByStationName(keyword) {
	    	console.log(keyword.substr(0,6))
	    　　localSearch.setSearchCompleteCallback(function (searchResult) {
	    		console.log(searchResult)
	    　　　　//var poi = searchResult.getPoi(0);
	    　　　　////document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat; //获取经度和纬度，将结果显示在文本框中
	    		var point = (searchResult['Oq']&&searchResult['Oq'].length>0)?searchResult['Oq'][0].point:(new BMap.Point(117.565297,33.547786));
	    　　　　	map.centerAndZoom(  point, 13);
	    　　});
	    　　localSearch.search(keyword.substr(0,6));
	    }

		return {
			refresh:addOverLay
		};
	})();

})
//baiduMap.refresh($('.selected-place').attr('data-addressid'));
